const jwt = require('jsonwebtoken');
const config = require('../config/config');

// 验证用户是否已登录
const isAuthenticated = (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];
  
  if (!token) {
    return res.status(401).json({ error: '未提供认证令牌' });
  }
  
  jwt.verify(token, config.jwt.secret, (err, user) => {
    if (err) {
      return res.status(403).json({ error: '无效或过期的令牌' });
    }
    
    req.user = user;
    next();
  });
};

// 验证是否为管理员
const isAdmin = (req, res, next) => {
  isAuthenticated(req, res, () => {
    if (req.user.userType !== 'admin') {
      return res.status(403).json({ error: '需要管理员权限' });
    }
    next();
  });
};

// 验证是否为员工
const isEmployee = (req, res, next) => {
  isAuthenticated(req, res, () => {
    if (req.user.userType !== 'employee') {
      return res.status(403).json({ error: '需要员工权限' });
    }
    next();
  });
};

module.exports = {
  isAuthenticated,
  isAdmin,
  isEmployee
};